/**
 * Game类 
 * 控制游戏启停
 * 初始化游戏参数
 * 切换场景
 */
(function (window) {
	let Game = window.Game = function(id){
		let self = this
		//得到画布
		this.c = document.querySelector(id)
		//得到上下文
		this.ctx = this.c.getContext('2d')
		//样式预设
		this.styleInit()
		//管子数组
		this.pipeArr = []
		//每个管子相隔的帧数
		this.pipeSpaceFno = 150
		//资源读取
		this.assetsLoad(function() {
			//加载场景
			require(['sceneManager'],function() {
				//场景实例化
				self.sceneManager = new SceneManager()
				//元素实例化(管子这里不实例化，要在更新时候pipe类中push到pipeArr数组中)
				self.bg = new Bg()
				self.land = new Land()
				self.bird = new Bird()
				//开启循环
				self.start()
			})
		})
		//游戏主循环
		this.mainLoop = null
		//帧编号
		this.fno = 1
		//帧开始时间
		this.fnTime1 = Date.now()
		//帧结束时间
		this.fnTime2 = Date.now()
		//每帧间隔时间
		this.fnInterval = 0
		//帧率
		this.fps = 0
		//背景运动速率
		this.bgSpeed = 1
		//管道运动速率
		this.pipeSpeed = 2
		//管道纵向间距
		this.vSpaceHeight = this.c.height*.25
		//小鸟下落速率
		this.birdDownSpeed = 0.4
		//小鸟上升速率
		this.birdFlySpeed = 0.2
		//游戏是否结束状态
		this.isGameOver = false		//默认未结束
		//当前分数
		this.score = 0
		//点击事件
		this.c.addEventListener('click',function(e) {
			self.clickEvent(e,self)
		})
		//按空格事件
		window.addEventListener('keydown',function (e) {
			if((e.code=='Space' || e.keyCode==32) && self.sceneManager.curScene && self.sceneManager.curScene == 2){
				self.bird.fno = 0	//小帧数重置
				self.bird.hasEnergy = true
			}   
		})
		//按键切换
		window.addEventListener('keypress',function (e) {
			//按Q切换背景
			if(e.code == 'KeyQ' || e.keyCode == 113){
				if(self.bg.oImg.src.indexOf('bg_day')!=-1){
					self.bg.oImg = myGame.bg_night 
					self.bg.fillStyleColor = '#008793'
				}else{
					self.bg.oImg = myGame.bg_day	//背景
					self.bg.fillStyleColor = '#4ec0ca'
				}
			}
			
			//按W切换小鸟
			if(e.code == 'KeyW' || e.keyCode == 119){
				self.bird.birdNth = self.bird.birdNth==0?1:(self.bird.birdNth==1?2:0)
				self.bird.birdImg0 = myGame['bird'+self.bird.birdNth+'_0']
				self.bird.birdImg1 = myGame['bird'+self.bird.birdNth+'_1']
				self.bird.birdImg2 = myGame['bird'+self.bird.birdNth+'_2']
			}
		})
	}
	
	//canvas样式预设
	Game.prototype.styleInit = function() {
		//设置宽高
		this.c.setAttribute('width',window.innerWidth)
		this.c.setAttribute('height',window.innerHeight)
	}
	
	//资源
	Game.prototype.assetsLoad = function(callback) {
		//计数器（资源加载进度）
		let loadNum = 0 , self = this
		require(['assets'],function(oAssets) {	//加载资源列表
			//遍历资源
			for (var i = 0; i < oAssets.images.length; i++) {
				self[oAssets.images[i].name] = new Image()
				self[oAssets.images[i].name].src = oAssets.images[i].url
				self[oAssets.images[i].name].onload = function(res) {
					loadNum++
					//提示文字
					let loadTxt = '正在加载 '+loadNum+'/'+oAssets.images.length+' 请稍后'
					self.ctx.clearRect(0,0,self.c.width,self.c.height)	//清屏
					self.ctx.fillStyle = 'black'
					self.ctx.font = '20px 微软雅黑'
					//居中渲染
					self.ctx.textAlign = 'center'
					let txtX = self.c.width/2 , txtY = self.c.height*(1-0.618)	//黄金分割
					self.ctx.fillText(loadTxt,txtX,txtY)
					//回调
					loadNum === oAssets.images.length && callback()
				}
			}
		})
	}
	
	//游戏主循环
	Game.prototype.start = function() {
		//清屏
		this.ctx.clearRect(0,0,this.c.width,this.c.height)
		
		//FPS计算
		this.fno % 2 && (this.fnTime1 = Date.now())
		this.fno % 2 || (this.fnTime2 = Date.now())
		this.fnInterval =  Math.abs(this.fnTime1-this.fnTime2)
		let nowFps = Math.round(1000 / this.fnInterval)
		//当帧率变化幅度大于等于10时再打印
		this.fps = this.fno>1 ? (Math.abs(this.fps-nowFps)>=10 ? nowFps : this.fps) : 0
		
		//场景渲染
		this.sceneManager.update()
		this.sceneManager.render()
		
		//游戏结束
		this.isGameOver && (this.sceneManager.curScene = 2)
		
		//打印帧信息
		let fno = 'FNO:'+this.fno , fps = 'FPS:'+this.fps
		this.ctx.font = "16px consolas"
		this.ctx.textAlign = 'left'
		this.ctx.fillText(fno,5,20)
		this.ctx.fillText(fps,5,40)
		
		//帧执行
		this.mainLoop = window.requestAnimationFrame(this.start.bind(this))
		this.fno++
	}
	
	//场景切换事件
	Game.prototype.clickEvent = function(e,self) {
		//判断当前场景号
		switch(this.sceneManager.curScene){
			case 2:
				//控制小鸟
				this.bird.fno = 0	//小帧数重置
				this.bird.hasEnergy = true
				break;
			case 3:
				//参数重置
				this.fno = 1
				this.bird.speed = 2	//重置小鸟速度
				this.pipeArr = []	//管子数组
				this.bird.fno = 0	//小帧数重置
				this.score = 0		//分数重置
				this.bird.d = 0		//旋转重置
				//再来一遍
				this.sceneManager.curScene = 1
				break;
			default:
				//开始游戏
				//点击按钮区域
				let isBtnClick = e.clientX >= this.sceneManager.scene1.btnX
				&& e.clientX <= this.sceneManager.scene1.btnX + self.button_play.width
				&& e.clientY >= this.sceneManager.scene1.btnY
				&& e.clientY <= this.sceneManager.scene1.btnY + self.button_play.height
				//执行场景2
				isBtnClick && (this.sceneManager.curScene = 2)
				break;
		}
	}
	
	//启动游戏
	window.myGame = new Game("#myCanvas")
})(window)
